// pages/publish/publish.js
import user_publish from '../../module/user_publish';
import user_login from '../../module/user_login';

const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    first: true,
    thing_id: false,
    edit: false,
    description: '',
    imgArr: [],
    _imgArr: [],
    price: '',
    old_price: '',
    classArr: ['学科资料', '图书', '寝室必备', '美妆洗护', '校园代步', '生活用品', '手机3C', '文体', '服装配饰', '其它'],
    classArr2: ['xuekeziliao', 'tushu', 'qingshibibei', 'meizhuangxihu', 'xiaoyuandaibu', 'shenghuoyongping', 'shouji3c', 'wenti', 'fushichuandai', 'other'],
    classArr_index: 0,
    contact: {
      phone: '',
      qq: '',
      address: ''
    },
    topic_id: null,
    publish_disabled: false,
    banner_data: {}
  },
  //************************************自定义事件************************* */
  /**
   * 发布闲置
   */
  publish() {
    let obj = {
      desc: this.data.description,
      qq: this.data.contact.qq,
      tel: this.data.contact.phone,
      place: this.data.contact.address,
      category: this.data.classArr2[this.data.classArr_index],
      price: this.data.price,
      ori_price: this.data.old_price
    };
    if (this.data.banner_data.id) {
      obj.topic_id = this.data.banner_data.id;
    }
    user_publish.publish(obj, this.data.thing_id).then(res => {
      console.log(res.data);
      if (res.data.err_code == 0) {
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 1000
        });
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          });
        }, 1000);
      } else {
        console.log(res);

        wx.showToast({
          title: '未知错误',
          image: '../../image/dele.png',
          duration: 1500
        });
      }
    });
  },
  /**
   * 检查 是否完成
   */
  check() {
    this.setData({
      publish_disabled:
        this.data.imgArr.length && this.data.description && this.data.price >= 0 && this.data.old_price >= 0 && this.data.contact.phone ? false : true
    });
  },
  /**
   * 联系人跳转
   */
  contactTo() {
    wx.navigateTo({
      url: '../contact/contact'
    });
  },
  /**
   * 描述 修改
   */
  descriptionChange(e) {
    this.setData({
      description: e.detail.value
    });
    this.check();
  },
  /**
   * 分类 修改
   */
  bindPickerChange(e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      [e.target.dataset.name]: e.detail.value
    });
    this.check();
  },
  /**
   * 选择图片
   */
  chooseImg() {
    let that = this;

    wx.chooseImage({
      count: 9 - that.data.imgArr.length,
      sizeType: ['compressed', 'original'], //所选的图片的尺寸 original-原图  compressed-压缩图
      sourceType: ['album', 'camera'],
      success(res) {
        // console.log(res);
        let _arr = res.tempFilePaths;
        console.log(_arr, that.data.imgArr);

        _arr = that.data.imgArr.concat(
          _arr.map((item, index) => {
            return {
              jindu: 0,
              dele: false,
              image: item
            };
          })
        );
        _arr = _arr.map((item, index) => {
          return new Promise((resolve, reject) => {
            if (item.dele == false) {
              item = item.image;
              user_publish
                .image(item, that.data.thing_id, res => {
                  // console.log(res)

                  // 成功回调
                  switch (res.statusCode) {
                    case 413:
                      // 提示信息
                      wx.showToast({
                        title: '文件过大',
                        image: '../../image/dele.png',
                        duration: 1500
                      });
                      // 删除错误图片
                      let _arr2 = that.data.imgArr;
                      _arr2.splice(index, 1);
                      that.setData({
                        imgArr: _arr2
                      });
                      resolve(false);
                      break;
                    case 400:
                      // 提示信息
                      wx.showToast({
                        title: '文件格式错误',
                        image: '../../image/dele.png',
                        duration: 1500
                      });
                      // 删除错误图片
                      let _arr400 = that.data.imgArr;
                      _arr400.splice(index, 1);
                      that.setData({
                        imgArr: _arr400
                      });
                      resolve(false);
                      break;

                    case 200:
                      let data = JSON.parse(res.data).data;
                      resolve(data);
                      break;
                  }
                })
                .onProgressUpdate(res => {
                  // 监听上传进度
                  let _arr3 = that.data.imgArr;
                  _arr3[index] = {
                    jindu: res.progress,
                    image: item,
                    id: index,
                    dele: false
                  };
                  that.setData({
                    imgArr: _arr3
                  });
                });
            } else {
              resolve(false);
            }
          });
        });
        Promise.all(_arr).then(res => {
          // console.log('all' + res)
          let arr = [];
          res.map(item => {
            if (item) {
              arr = arr.concat(item);
            }
          });
          // 去重
          arr = [...new Set(arr.map(item => JSON.stringify(item)))]
            .map(item => JSON.parse(item))
            .map(item => {
              return {
                id: item.id,
                image: app.globalData.baseURL + '/' + item.image,
                dele: true,
                jindu: 100
              };
            });
          that.setData(
            {
              imgArr: arr.length ? arr : that.data.imgArr
            },
            () => {
              that.check();
            }
          );
        });
      },
      fail(err) {
        console.log(err);
      }
    });
  },
  /**
   * 图片点击
   */
  imgClick(e) {
    let that = this,
      arr = that.data.imgArr.map(item => item.image);
    wx.previewImage({
      current: arr[e.target.dataset.num], // 当前显示图片的http链接
      urls: arr // 需要预览的图片http链接列表
    });
  },
  /**
   * 图片删除
   */
  imgDele(e) {
    let that = this;
    console.log(e.target.dataset.id);
    user_publish.deleImage(e.target.dataset.id, that.data.thing_id).then(res => {
      // console.log(res)
      if (res.data.err_code == 0) {
        let arr = [];
        that.data.imgArr.map(item => {
          if (item.id != e.target.dataset.id) {
            arr.push(item);
          }
        });
        that.setData({
          imgArr: arr
        });
      }
    });

    this.check();
  },
  /**
   * 价格 格式限定
   *
   */
  priceChange(e) {
    this.setData({
      [e.target.dataset.name]: (/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(e.detail.value) ? e.detail.value : this.data[e.target.dataset.name]) * 1
    });
    this.check();
  },

  //************************************周期************************** */
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;

    user_login.checkSSF(
      () => {
        if (options.data) {
          let data = JSON.parse(options.data);
          //获取物品token
          console.log(data);

          that.setData({
            edit: true,
            description: data.desc,
            price: data.price,
            old_price: data.ori_price,
            contact: {
              phone: data.contacts.tel,
              qq: data.contacts.qq,
              address: data.contacts.address
            },
            classArr_index: data.category_num - 1,
            imgArr: data.images_obj.map(item => {
              return {
                id: item.image_id,
                image: app.globalData.baseURL + '/' + item.image,
                dele: true,
                jindu: 100
              };
            }),
            thing_id: data.thing_id
          });
        } else {
          user_publish.preCreate();
        }
      },
      () => {
        wx.showModal({
          title: '您未绑定教务系统！',
          content: '是否前往绑定？',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '../login/login'
              });
              that.setData({
                first: false
              });
            } else if (res.cancel) {
              wx.navigateBack();
            }
          }
        });
      }
    );
    // 专题
    if (options.banner_data) {
      let banner_data = JSON.parse(options.banner_data);
      console.log(banner_data);
      this.setData({
        banner_data: banner_data
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this;
    //联系人 首次填写 从缓存中读取
    if (!that.data.edit) {
      wx.getStorage({
        key: 'contact',
        success(res) {
          that.setData({
            contact: {
              phone: res.data.phone,
              qq: res.data.qq,
              address: res.data.address[0][res.data.addressIndex[0]] + res.data.address[1][res.data.addressIndex[1]]
            }
          });
          that.check();
        }
      });
    }
    user_login.checkSSF(
      () => {},
      () => {
        if (!this.data.first) {
          wx.navigateBack();
        }
      }
    );
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {}
});
